package cn.cmkj.auction.ui.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;


import com.google.gson.Gson;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.util.LogUtil;
import org.xutils.http.HttpMethod;
import org.xutils.http.RequestParams;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import cn.cmkj.auction.R;
import cn.cmkj.auction.adapter.MainCartAdapter;
import cn.cmkj.auction.app.Urls;
import cn.cmkj.auction.data.db.User;
import cn.cmkj.auction.data.http.Cart;
import cn.cmkj.auction.data.http.ShuhuaOrder;
import cn.cmkj.auction.event.LoginEvent;
import cn.cmkj.auction.ui.MainActivity;
import cn.cmkj.auction.ui.OrderDetailActivity;
import cn.cmkj.auction.ui.ShuhuaDetailActivity;
import cn.cmkj.auction.utils.HttpCallback;
import cn.cmkj.auction.widget.swipe.SwipeMenu;
import cn.cmkj.auction.widget.swipe.SwipeMenuBridge;
import cn.cmkj.auction.widget.swipe.SwipeMenuCreator;
import cn.cmkj.auction.widget.swipe.SwipeMenuItem;
import cn.cmkj.auction.widget.swipe.SwipeMenuItemClickListener;
import cn.cmkj.auction.widget.swipe.SwipeMenuRecyclerView;
import cn.cmkj.auction.widget.swipeRecyclerView.MySwipeMenuRecyclerView;

/**
 * Created by cunguoyao on 2017/8/13.
 */
@ContentView(R.layout.fragment_main_cart)
public class MainCartFragment extends BaseFragment implements MySwipeMenuRecyclerView.OnLoadListener, View.OnClickListener, View.OnTouchListener {

    @ViewInject(R.id.swipeRecyclerView)
    private MySwipeMenuRecyclerView swipeMenuRecyclerView;
    @ViewInject(R.id.cart_checkbox)
    private CheckBox chooseCheckbox;
    @ViewInject(R.id.cart_total_price)
    private TextView totalPriceText;
    @ViewInject(R.id.layout_count)
    private RelativeLayout goOrderLayout;
    @ViewInject(R.id.cart_total_count)
    private TextView totalCountText;
    @ViewInject(R.id.empty_data_layout)
    private LinearLayout emptyDataLayout;
    @ViewInject(R.id.go_shop)
    private Button goShoppingBtn;
    @ViewInject(R.id.cart_bottom)
    private RelativeLayout cartBottomLayout;
    private int totalCount;
    private BigDecimal totalPrice;

    private List<Cart> mData;
    private MainCartAdapter mainCartAdapter;
    private boolean requesting = false;

    public static MainCartFragment create() {
        MainCartFragment f = new MainCartFragment();
        Bundle args = new Bundle();
        //args.putInt("type", type);
        f.setArguments(args);
        return f;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        mData = new ArrayList<>();
        mainCartAdapter = new MainCartAdapter(getActivity(), this, mData);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = x.view().inject(this, inflater, container);
        swipeMenuRecyclerView.getRecyclerView().setLayoutManager(new LinearLayoutManager(getActivity()));
        //((SwipeMenuRecyclerView)swipeMenuRecyclerView.getRecyclerView()).setLongPressDragEnabled(true); // 开启拖拽。
        //((SwipeMenuRecyclerView)swipeMenuRecyclerView.getRecyclerView()).setItemViewSwipeEnabled(true); // 开启滑动删除。
        swipeMenuRecyclerView.setAdapter(mainCartAdapter);
        SwipeMenuRecyclerView menuRecyclerView = ((SwipeMenuRecyclerView)swipeMenuRecyclerView.getRecyclerView());
        menuRecyclerView.setSwipeMenuCreator(swipeMenuCreator);
        menuRecyclerView.setSwipeMenuItemClickListener(menuItemClickListener);
        menuRecyclerView.smoothOpenRightMenu(0);
        goShoppingBtn.setOnClickListener(this);
        goOrderLayout.setOnClickListener(this);
        //不允许加载更多
        swipeMenuRecyclerView.setLoadMoreEnable(false);
        swipeMenuRecyclerView.setOnLoadListener(this);
        swipeMenuRecyclerView.setRefreshing(true);
        init();
        return view;
    }

    /**
     * 菜单创建器。在Item要创建菜单的时候调用。
     */
    private SwipeMenuCreator swipeMenuCreator = new SwipeMenuCreator() {
        @Override
        public void onCreateMenu(SwipeMenu swipeLeftMenu, SwipeMenu swipeRightMenu, int viewType) {
            SwipeMenuItem deleteItem = new SwipeMenuItem(getActivity())
                    .setBackground(R.color.swipe_menu_red) // 图标。
                    .setText("删除") // 文字。
                    .setTextSize(16) // 文字大小。
                    .setTextColor(getResources().getColor(R.color.white)) // 文字颜色。
                    .setHeight(LinearLayout.LayoutParams.MATCH_PARENT)
                    .setWidth(250);
                    swipeRightMenu.addMenuItem(deleteItem);// 添加一个按钮到右侧侧菜单。.
        }
    };

    private SwipeMenuItemClickListener menuItemClickListener = new SwipeMenuItemClickListener() {
        @Override
        public void onItemClick(SwipeMenuBridge menuBridge) {
            int menuPosition = menuBridge.getPosition();
            Cart cart = mainCartAdapter.getItem(menuBridge.getAdapterPosition());
            if(menuPosition == 0) {
                removeCart(cart, menuBridge.getAdapterPosition());
            }
        }
    };

    @Override
    public void onRefresh() {
        if(!requesting) {
            mData.clear();
            mainCartAdapter.notifyDataSetChanged();
            fetchData();
        }
    }

    @Override
    public void onLoadMore() {
    }

    public void fetchData() {
        requesting = true;
        User user = getAccount();
        if(user == null) {
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    //结束后停止刷新
                    swipeMenuRecyclerView.complete();
                    requesting = false;
                }
            }, 1000);
        }else {
            RequestParams params = new RequestParams(Urls.api);
            params.addParameter("method", Urls.cartInfo);
            params.addParameter("accesstoken", user.getToken());
            params.addParameter("member_id", user.getId());
            x.http().request(HttpMethod.POST, params, new HttpCallback(getActivity()) {
                @Override
                public void success(String s) {
                    requesting = false;
                    swipeMenuRecyclerView.complete();
                    JSONObject jsonObject = null;
                    try {
                        jsonObject = new JSONObject(s);
                        JSONObject json = jsonObject.optJSONObject("data");
                        if(json != null && json.has("object")) {
                            showData();
                            JSONObject jsonObject1 = json.optJSONObject("object");
                            JSONArray jsonArray = jsonObject1.optJSONArray("goods");
                            List<Cart> temp = Cart.parseJsonArray(jsonArray);
                            mData.addAll(temp);
                            mainCartAdapter.notifyDataSetChanged();
                            if (Urls.pageSize > temp.size()) {
                                swipeMenuRecyclerView.setLoadMoreEnable(false);
                            } else {
                                swipeMenuRecyclerView.setLoadMoreEnable(true);
                            }
                        }else {
                            showEmpty();
                            swipeMenuRecyclerView.setLoadMoreEnable(false);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void error(Throwable ex, String msg, boolean isOnCallback) {
                    requesting = false;
                    swipeMenuRecyclerView.complete();
                    if (ex != null) ex.printStackTrace();
                    LogUtil.e("---onError-----" + "onError");
                    Toast.makeText(getActivity(), TextUtils.isEmpty(msg) ? "请求失败" : msg, Toast.LENGTH_SHORT).show();
                }

                @Override
                public void cancel(CancelledException cex) {
                    requesting = false;
                    swipeMenuRecyclerView.complete();
                    LogUtil.e("---onCancelled-----" + "onCancelled");
                }

                @Override
                public void finished() {
                    requesting = false;
                    swipeMenuRecyclerView.complete();
                }
            });
        }
    }

    private void init() {
        chooseCheckbox.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                boolean check = chooseCheckbox.isChecked();
                if(mData != null && mData.size() > 0) {
                    List<Cart> temp = new ArrayList<>();
                    for (Cart cart : mData) {
                        cart.setChecked(check);
                        temp.add(cart);
                    }
                    mData.clear();
                    mData.addAll(temp);
                    mainCartAdapter.notifyDataSetChanged();
                    onCheck();
                }
            }
        });
    }

    public void onCheck() {
        totalCount = 0;
        totalPrice = BigDecimal.valueOf(0);
        if(mData != null && mData.size() > 0) {
            for(Cart cart : mData) {
                if(cart.isChecked()) {
                    totalCount = totalCount + 1;
                    totalPrice = totalPrice.add(cart.getSalePrice());
                }
            }
            if(totalCount == mData.size()) {
                chooseCheckbox.setChecked(true);
            }else {
                chooseCheckbox.setChecked(false);
            }
            totalCountText.setText("共" + totalCount + "幅，下单");
            totalPriceText.setText("总价：" + totalPrice.doubleValue() + "元");
        }
    }

    private void removeCart(Cart cart, final int position) {
        RequestParams params = new RequestParams(Urls.api);
        params.addParameter("method", Urls.removeCart);
        params.addParameter("type", "goods");
        params.addParameter("remove_all", "false");
        params.addParameter("goods_id", cart.getId());
        params.addParameter("product_id", cart.getProductId());
        User user = getAccount();
        if(user == null) {
            showLoginDialog(getActivity());
        }else {
            showLoading(true);
            params.addParameter("accesstoken", user.getToken());
            params.addParameter("member_id", user.getId());
            x.http().request(HttpMethod.POST, params, new HttpCallback(getActivity()) {
                @Override
                public void success(String s) {
                    dismissLoading();
                    JSONObject jsonStr = null;
                    try {
                        jsonStr = new JSONObject(s);
                        JSONObject json = jsonStr.optJSONObject("data");
                        boolean success = json.optBoolean("status");
                        if(success) {
                            //建议这么操作 不会出问题
                            mData.remove(position);
                            mainCartAdapter.notifyItemRemoved(position);
                            if(mData == null || mData.size() <= 0) {
                                showEmpty();
                            }else {
                                showData();
                            }
                        }
                        String toast = json.optString("message");
                        if(!TextUtils.isEmpty(toast)) {
                            Toast.makeText(getActivity(), toast, Toast.LENGTH_SHORT).show();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void error(Throwable ex, String msg, boolean isOnCallback) {
                    dismissLoading();
                    if(!TextUtils.isEmpty(msg)) {
                        Toast.makeText(getActivity(), msg, Toast.LENGTH_SHORT).show();
                    }
                }

                @Override
                public void cancel(CancelledException e) {
                    dismissLoading();
                }

                @Override
                public void finished() {
                    requesting = false;
                    swipeMenuRecyclerView.complete();
                }
            });
        }
    }

    private void showData() {
        swipeMenuRecyclerView.setVisibility(View.VISIBLE);
        emptyDataLayout.setVisibility(View.GONE);
        cartBottomLayout.setVisibility(View.VISIBLE);
    }

    private void showEmpty() {
        swipeMenuRecyclerView.setVisibility(View.VISIBLE);
        emptyDataLayout.setVisibility(View.VISIBLE);
        cartBottomLayout.setVisibility(View.GONE);
    }

    class BuyGoods {
        String goods_id;
        String product_id;
    }

    private void orderPre() {
        List<BuyGoods> list = new ArrayList<>();
        if(mData != null && mData.size() > 0) {
            for(Cart cart : mData) {
                BuyGoods buyGoods = new BuyGoods();
                buyGoods.goods_id = ""+cart.getId();
                buyGoods.product_id = ""+cart.getProductId();
                list.add(buyGoods);
            }
        }
        RequestParams params = new RequestParams(Urls.api);
        params.addParameter("method", Urls.orderPre);
        params.addParameter("isfastbuy", "false");
        String json = new Gson().toJson(list);
        LogUtil.e("---buy_goods--" + json);
        params.addParameter("buy_goods", json);
        User user = getAccount();
        if(user == null) {
            showLoginDialog(getActivity());
        }else {
            showLoading(true);
            params.addParameter("accesstoken", user.getToken());
            params.addParameter("member_id", user.getId());
            x.http().request(HttpMethod.POST, params, new HttpCallback(getActivity()) {
                @Override
                public void success(String s) {
                    dismissLoading();
                    JSONObject jsonStr = null;
                    try {
                        jsonStr = new JSONObject(s);
                        JSONObject json = jsonStr.optJSONObject("data");
                        ShuhuaOrder order = ShuhuaOrder.parseFromJsonByPreOrder(json);
                        if(order != null) {
                            Intent intent = new Intent(getActivity(), OrderDetailActivity.class);
                            intent.putExtra(OrderDetailActivity.FROM, OrderDetailActivity.FROM_PRE_ORDER);
                            intent.putExtra("order", order);
                            startActivityForResult(intent, 1);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void error(Throwable ex, String msg, boolean isOnCallback) {
                    dismissLoading();
                    if(!TextUtils.isEmpty(msg)) {
                        Toast.makeText(getActivity(), msg, Toast.LENGTH_SHORT).show();
                    }
                }

                @Override
                public void cancel(CancelledException e) {
                    dismissLoading();
                }

                @Override
                public void finished() {
                    dismissLoading();
                }
            });

        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.go_shop:
                ((MainActivity)getActivity()).performChecked(R.id.b2);
                break;
            case R.id.layout_count:
                if(totalCount > 0) {
                    orderPre();
                }
                break;
        }
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        if (requesting) {
            return true;
        } else {
            return false;
        }
    }

    @Subscribe(threadMode = ThreadMode.POSTING)
    public void onEventBus(LoginEvent event){
        Toast.makeText(getActivity(), "event.getType()=" + event.getType(), Toast.LENGTH_SHORT).show();
        if (event.getType() == LoginEvent.LOGIN_SUCCESS) {
            account = getAccount();
            if(account != null) {
                onRefresh();
            }
        }else if (event.getType() == LoginEvent.LOGOUT_SUCCESS) {
            mData.clear();
            mainCartAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
